<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>AI对话助手</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    .message {
      animation: fadeIn 0.3s ease;
    }
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }
    .typing-indicator span {
      display: inline-block;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background-color: #9CA3AF;
      margin-right: 4px;
      animation: bounce 1.4s infinite ease-in-out;
    }
    .typing-indicator span:nth-child(2) { animation-delay: 0.2s; }
    .typing-indicator span:nth-child(3) { animation-delay: 0.4s; }
    @keyframes bounce {
      0%, 60%, 100% { transform: translateY(0); }
      30% { transform: translateY(-5px); }
    }
    .scrollbar-hide {
      -ms-overflow-style: none;
      scrollbar-width: none;
    }
    .scrollbar-hide::-webkit-scrollbar {
      display: none;
    }
  </style>
</head>
<body class="bg-gray-100 h-screen flex">
  <div class="flex w-full max-w-6xl mx-auto h-screen">
    <!-- 侧边栏 -->
    <div class="w-64 bg-white border-r flex flex-col">
      <div class="p-4 border-b">
        <h2 class="text-lg font-semibold text-gray-800">对话历史</h2>
        <button id="newChatBtn" class="mt-3 w-full bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-colors flex items-center justify-center">
          <span class="mr-2">+</span> 新建对话
        </button>
      </div>
      <div id="chatHistoryList" class="flex-1 overflow-y-auto p-2">
        <!-- 聊天历史列表将通过JS生成 -->
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="flex-1 flex flex-col">
      <!-- 头部 -->
      <header class="bg-white shadow-sm py-4 px-6">
        <h1 class="text-xl font-bold text-gray-800">资料检索AI助手</h1>
      </header>

      <!-- 聊天内容区域 -->
      <div id="chatContainer" class="flex-1 overflow-hidden flex flex-col bg-gray-50">
        <div id="messagesContainer" class="flex-1 overflow-y-auto p-6 space-y-4 scrollbar-hide">
          <div id="emptyState" class="flex flex-col items-center justify-center h-full text-gray-500">
            <div class="text-5xl mb-4">🤖</div>
            <h3 class="text-xl font-medium mb-2">开始对话</h3>
            <p class="text-center">输入消息与AI助手交流</p>
          </div>
          <div id="messagesList" class="hidden"></div>
        </div>

        <!-- 输入区域 -->
        <div class="border-t p-4 bg-white">
          <div class="flex items-end space-x-2">
            <textarea 
              id="messageInput" 
              placeholder="输入消息..." 
              class="flex-1 border border-gray-300 rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
              rows="1"
            ></textarea>
            <button 
              id="sendButton" 
              class="bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-6 rounded-lg transition-colors disabled:bg-blue-400"
            >
              发送
            </button>
          </div>
          <p class="text-xs text-gray-500 mt-2 text-center">
            按 Enter 发送，Shift+Enter 换行
          </p>
        </div>
      </div>
    </div>
  </div>

  <script>
    // 全局变量
    let chatHistory = JSON.parse(localStorage.getItem('chatHistory')) || [];
    let currentChatId = null;
    let eventSource = null;
    let isReceiving = false;

    // DOM 元素
    const chatHistoryList = document.getElementById('chatHistoryList');
    const messagesContainer = document.getElementById('messagesContainer');
    const messagesList = document.getElementById('messagesList');
    const emptyState = document.getElementById('emptyState');
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');
    const newChatBtn = document.getElementById('newChatBtn');

    // 初始化
    function init() {
      // 如果没有聊天记录，创建第一个聊天
      if (chatHistory.length === 0) {
        createNewChat();
      } else {
        // 激活第一个聊天
        currentChatId = chatHistory[0].id;
      }

      // 渲染聊天历史
      renderChatHistory();
      renderCurrentChat();

      // 绑定事件监听器
      sendButton.addEventListener('click', handleSendMessage);
      messageInput.addEventListener('keydown', handleInputKeyDown);
      messageInput.addEventListener('input', autoResizeTextarea);
      newChatBtn.addEventListener('click', createNewChat);
    }

    // 自动调整文本框高度
    function autoResizeTextarea() {
      this.style.height = 'auto';
      this.style.height = Math.min(this.scrollHeight, 200) + 'px';
    }

    // 创建新聊天
    function createNewChat() {
      const newChat = {
        id: Date.now().toString(),
        title: '新对话',
        messages: [],
        timestamp: new Date().toISOString()
      };

      chatHistory.unshift(newChat);
      currentChatId = newChat.id;

      saveToLocalStorage();
      renderChatHistory();
      renderCurrentChat();
    }

    // 渲染聊天历史列表
    function renderChatHistory() {
      chatHistoryList.innerHTML = '';

      chatHistory.forEach(chat => {
        const chatItem = document.createElement('div');
        chatItem.className = `p-3 rounded-lg mb-2 cursor-pointer flex justify-between items-center ${
          chat.id === currentChatId 
            ? 'bg-blue-100 text-blue-800' 
            : 'hover:bg-gray-100'
        }`;
        chatItem.dataset.id = chat.id;

        // 获取对话的第一条消息作为标题（如果标题还是默认值）
        if (chat.title === '新对话' && chat.messages.length > 0) {
          const firstUserMessage = chat.messages.find(msg => msg.role === 'user');
          if (firstUserMessage) {
            chat.title = firstUserMessage.content.substring(0, 30) + (firstUserMessage.content.length > 30 ? '...' : '');
          }
        }

        chatItem.innerHTML = `
          <div class="truncate flex-1">${chat.title}</div>
          <div class="flex space-x-1 opacity-0 group-hover:opacity-100 transition-opacity">
            <button class="edit-btn p-1 rounded hover:bg-gray-200" title="重命名">✏️</button>
            <button class="delete-btn p-1 rounded hover:bg-red-200" title="删除">🗑️</button>
          </div>
        `;

        // 点击选择聊天
        chatItem.addEventListener('click', (e) => {
          if (!e.target.classList.contains('edit-btn') && !e.target.classList.contains('delete-btn')) {
            currentChatId = chat.id;
            renderChatHistory();
            renderCurrentChat();
          }
        });

        // 重命名按钮
        const editBtn = chatItem.querySelector('.edit-btn');
        editBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          const newTitle = prompt('请输入对话名称:', chat.title);
          if (newTitle !== null && newTitle.trim() !== '') {
            chat.title = newTitle.trim();
            saveToLocalStorage();
            renderChatHistory();
          }
        });

        // 删除按钮
        const deleteBtn = chatItem.querySelector('.delete-btn');
        deleteBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          if (confirm('确定要删除这个对话吗？此操作不可撤销。')) {
            chatHistory = chatHistory.filter(c => c.id !== chat.id);

            if (currentChatId === chat.id) {
              currentChatId = chatHistory.length > 0 ? chatHistory[0].id : null;
            }

            saveToLocalStorage();
            renderChatHistory();
            renderCurrentChat();
          }
        });

        chatHistoryList.appendChild(chatItem);
      });
    }

    // 渲染当前聊天内容
    function renderCurrentChat() {
      if (!currentChatId) {
        emptyState.classList.remove('hidden');
        messagesList.classList.add('hidden');
        return;
      }

      const chat = chatHistory.find(c => c.id === currentChatId);
      if (!chat) return;

      if (chat.messages.length === 0) {
        emptyState.classList.remove('hidden');
        messagesList.classList.add('hidden');
        return;
      }

      emptyState.classList.add('hidden');
      messagesList.classList.remove('hidden');
      messagesList.innerHTML = '';

      chat.messages.forEach(message => {
        const messageElement = document.createElement('div');
        messageElement.className = `message max-w-[85%] p-4 rounded-xl ${
          message.role === 'user' 
            ? 'ml-auto bg-blue-600 text-white rounded-br-none' 
            : 'mr-auto bg-gray-100 text-gray-800 rounded-bl-none'
        }`;

        const sender = message.role === 'user' ? '' : '资料检索AI助手';
        const icon = message.role === 'user' ? '' : '🤖';

        messageElement.innerHTML = `
          <div class="font-semibold mb-1">${icon} ${sender}</div>
          <div class="whitespace-pre-wrap">${message.content}</div>
        `;

        messagesList.appendChild(messageElement);
      });

      // 滚动到底部
      scrollToBottom();
    }

    // 处理发送消息
    function handleSendMessage() {
      const message = messageInput.value.trim();
      if (!message || isReceiving) return;

      // 获取当前聊天
      let chat = chatHistory.find(c => c.id === currentChatId);
      if (!chat) {
        // 如果没有找到当前聊天，创建一个
        createNewChat();
        chat = chatHistory.find(c => c.id === currentChatId);
      }

      // 添加用户消息到对话
      const userMessage = {
        role: 'user',
        content: message,
        timestamp: new Date().toISOString()
      };
      chat.messages.push(userMessage);

      // 如果是新对话，更新标题
      if (chat.title === '新对话') {
        chat.title = message.substring(0, 30) + (message.length > 30 ? '...' : '');
        renderChatHistory();
      }

      saveToLocalStorage();
      renderCurrentChat();

      // 清空输入框并重置高度
      messageInput.value = '';
      messageInput.style.height = 'auto';

      // 调用API获取AI响应
      callAIStreamAPI(message);
    }

    // 处理输入框键盘事件
    function handleInputKeyDown(e) {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        handleSendMessage();
      }
    }

    // 调用AI流式API（根据新接口格式）
    function callAIStreamAPI(message) {
      // 设置接收状态
      isReceiving = true;
      sendButton.disabled = true;

      // 获取当前聊天
      const chat = chatHistory.find(c => c.id === currentChatId);
      if (!chat) return;

      // 显示AI正在输入指示器
      const typingIndicator = createTypingIndicator();
      messagesList.appendChild(typingIndicator);
      scrollToBottom();

      // 构建API URL - 注意：接口路径已更新为 /api/ollama/generate_stream_rag
      const apiUrl = `http://127.0.0.1:9910/api/ollama/generate_stream_rag?message=${encodeURIComponent(message)}`;

      // 创建EventSource连接
      eventSource = new EventSource(apiUrl);

      // 存储AI消息的完整内容
      let aiFullResponse = '';

      // 处理接收到的消息
      eventSource.onmessage = function(event) {
        try {
          const data = JSON.parse(event.data);
          // 新接口字段：content 和 finished
          if (data.content !== undefined && data.type === 'TEXT') {
            aiFullResponse += data.content;

            // 更新AI消息显示
            typingIndicator.innerHTML = `
              <div class="font-semibold mb-1">🤖 资料检索AI助手</div>
              <div class="whitespace-pre-wrap">${aiFullResponse}</div>
            `;

          }

          if(data.type === 'FILE'){
            aiFullResponse+='<br>以上内容来源文件：<br>'
            data.content.forEach(file=>{
              console.log(file)
              aiFullResponse+=`<div style="display: flex; align-items: center;"><img width="20"  src="images/${file.fileType}.png"/><a href="${file.fileUrl}" target="_blank" style="color: #4f46e5">${file.fileName}</a></div>`
              typingIndicator.innerHTML = `
              <div class="font-semibold mb-1">🤖 资料检索AI助手</div>
              <div class="whitespace-pre-wrap">文件名称</div>
            `;
            })
          }
          scrollToBottom();
          // 检查结束标识 - finished 为 true 表示结束
          if (data.finished === true) {
            finishAIResponse(aiFullResponse, typingIndicator, chat);
          }


        } catch (e) {
          console.error('处理流数据错误:', e);
          console.error('错误数据:', event.data);
        }
      };

      // 处理错误
      eventSource.onerror = function(err) {
        console.error('EventSource 失败:', err);
        eventSource.close();
        finishAIResponse('抱歉，AI响应出现错误，请稍后再试。', typingIndicator, chat);
      };
    }

    // 创建输入指示器
    function createTypingIndicator() {
      const indicator = document.createElement('div');
      indicator.className = 'message max-w-[85%] mr-auto bg-gray-100 text-gray-800 rounded-xl rounded-bl-none p-4';
      indicator.innerHTML = `
        <div class="font-semibold mb-1">🤖 资料检索AI助手</div>
        <div class="typing-indicator">
          <span></span>
          <span></span>
          <span></span>
        </div>
      `;
      return indicator;
    }

    // 完成AI响应
    function finishAIResponse(content, typingIndicator, chat) {
      // 关闭EventSource连接
      if (eventSource) {
        eventSource.close();
        eventSource = null;
      }

      // 从指示器获取最终内容
      if (content) {
        typingIndicator.innerHTML = `
          <div class="font-semibold mb-1">🤖 AI 助手</div>
          <div class="whitespace-pre-wrap">${content}</div>
        `;
      }

      // 添加AI消息到对话记录
      if (content) {
        const aiMessage = {
          role: 'ai',
          content: content,
          timestamp: new Date().toISOString()
        };
        chat.messages.push(aiMessage);
        saveToLocalStorage();
      }

      // 重置状态
      isReceiving = false;
      sendButton.disabled = false;

      // 聚焦输入框
      messageInput.focus();
    }

    // 滚动到底部
    function scrollToBottom() {
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    // 保存到本地存储
    function saveToLocalStorage() {
      localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', init);
  </script>
</body>
</html>
